export default {
  beforeMount () {
    this.setAreaId()
  },
  mounted () {
    this.setTableHeight()
    window.addEventListener('resize', this.setTableHeight)
    this.setRowCheckEvent()

    // 外部自定义缩放
    if (this.renderTable) {
      let fn = this.customResizeFn
      fn()
      window.addEventListener('resize', fn)
    }
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.setTableHeight)
    window.removeEventListener('keydown', this.onTableKeydown)
    window.removeEventListener('keyup', this.onTableKeyup)

    // 外部自定义缩放
    if (this.renderTable) {
      window.removeEventListener('resize', this.customResizeFn)
    }
  },
  methods: {
    setAreaId () {
      let query = this.$route.query
      let ids = (query.id || '').split('-')
      if (ids && ids.length) {
        this.areaId = parseInt(ids[0])
      }
    },
    setTableHeight () {
      // totalSpace 剩余空白空间
      this.tableHeight = window.innerHeight - (this.totalSpace || 200)
      this.$emit('update:maxHeight', this.tableHeight)
    },
    // -----------------------------------Table重绘------------------------------------------------
    customResizeFn () {
      // 标准是1366
      let width = window.innerWidth
      this.$store.commit('setWindowWidth', width)
      // 默认使用originColumns和columns
      let originColumnsKey = this.originColumnsKey || 'originColumns'
      let columnsKey = this.columnsKey || 'columns'

      let columns
      if (width >= 1366) {
        columns = this[originColumnsKey]
      } else {
        columns = []
        this[originColumnsKey].forEach(item => {
          if (!item.windowWidth || width >= item.windowWidth) {
            columns.push(item)
          }
        })
      }

      this[columnsKey] = columns
    },
    toggleLoading (loading = true) {
      this.loading = loading
    },
    // -----------------------------------Table事件------------------------------------------------
    getIdKey () {
      return this.page.idKey || 'id'
    },
    getRowClass (row, index) {
      let checkboxMap = this.checkboxMap
      if (checkboxMap) {
        let key = this.page.idKey || 'id'
        if (checkboxMap[row[key]]) {
          return 'row-checked'
        } else {
          return ''
        }
      } else {
        if (row._checked) {
          return 'row-checked'
        } else {
          return ''
        }
      }
    },
    // 传递过来的rows是Table里面复制的list，和page.list不是同一个对象（该方法适用于不需要判断checkbox是否可以点击）
    selectionChange (rows = []) {
      let page = this.page
      let list = page.list
      // 外部定义key
      let key = page.idKey || 'id'

      let ids = rows.map(item => {
        return item[key]
      })

      this[page.selectedIdsKey || 'selectedIds'] = ids
      let item
      for (let i = 0; i < list.length; i++) {
        item = list[i]
        item._checked = ids.indexOf(item[key]) !== -1
      }
    },
    clickRow (row, index) {
      let page = this.page
      // 外部定义key
      let key = this.getIdKey()
      let id = row[key]

      if (!this.checkable(row)) {
        return
      }

      if (!this.checkboxMap) {
        let ref = page.ref || 'table'
        let table = this.$refs[ref]
        table.toggleSelect(index)
      } else {
        this.toggleCheckbox(id)
      }
    },
    resetCheckboxList () {
      if (this.checkboxMap) {
        this.checkAll = false
        this.checkboxMap = {}
      }

      if (this.selectedIds) {
        this.selectedIds = []
      }

      if (this.selectedList) {
        this.selectedList = []
      }
    },
    renderCheckboxColumn () {
      let that = this
      return {
        title: '',
        width: 50,
        ailgn: 'center',
        render (h, param) {
          let row = param.row
          let key = that.getIdKey()

          if (!that.checkable(param.row)) {
            return
          }

          return h('Checkbox', {
            props: {
              value: that.checkboxMap[row[key]]
            },
            on: {
              'on-change' (value) {
                that.toggleCheckbox(row[key], value)
              }
            }
          }, '')
        }
      }
    },
    checkable (item) {
      return true
    },
    // 序号列
    renderIndexCol () {
      let that = this
      return {
        title: '序号',
        width: 60,
        align: 'center',
        render (h, param) {
          let page = that.page
          if (page.total) {
            return h('span', page.pageSize * (page.pageNum - 1) + param.index + 1)
          } else {
            return h('span', param.index + 1)
          }
        }
      }
    },
    setCheckboxMap () {
      let map = {}
      let page = this.page
      let key = page.idKey || 'id'
      page.list.forEach(item => {
        if (this.checkable(item)) {
          map[item[key]] = !!item._checked
        }
      })

      this.checkboxMap = map
      this.checkRows()
    },
    setSelectedList () {
      let selectedIds = this.selectedIds
      if (!selectedIds.length) {
        this.tipUtil.warning('请至少选择一条数据')
        return
      }

      let key = this.page.idKey || 'id'
      this.selectedList = this.page.list.filter(item => {
        if (this.checkboxMap[item[key]]) {
          return item
        }
      })

      return !!selectedIds.length
    },
    updateSelectedId (id) {
      this.toggleCheckbox(id)
      let key = this.page.idKey || 'id'

      let selectedList = []
      let map = this.checkboxMap
      this.page.list.forEach(item => {
        id = item[key]
        if (map[id]) {
          selectedList.push(item)
        }
      })

      this.selectedList = selectedList
    },
    toggleCheckAll (checked) {
      let map = this.checkboxMap

      for (let key in map) {
        map[key] = checked
      }

      this.checkRows()
    },
    // 不能使用_checkboxMap
    toggleCheckbox (id, value) {
      let map = this.checkboxMap
      if (typeof value === 'boolean') {
        map[id] = value
      } else {
        map[id] = !map[id]
      }

      let checkAll = true
      for (let key in map) {
        if (!map[key]) {
          checkAll = false
        }
      }

      this.checkAll = checkAll
      this.checkRows()
    },
    checkRows () {
      let map = this.checkboxMap
      let ids = []
      let page = this.page
      let list = page.list
      let idKey = page.idKey || 'id'

      let hasCheckbox = false
      // 再次检测
      let checkAll = true
      for (let key in map) {
        hasCheckbox = true
        if (map[key]) {
          ids.push(key)
        } else {
          checkAll = false
        }
      }

      let ref = page.ref || 'table'
      let table = this.$refs[ref].$el
      let item
      let rows = table.querySelectorAll('.ivu-table-row')
      let classList
      for (let i = 0; i < list.length; i++) {
        item = list[i]
        let _checked = map[item[idKey]]
        if (item._checked !== _checked) {
          // 不能在page.list上修改_checked，必须使用一个map来监控class
          // item._checked = _checked
          let row = rows[i]
          if (!row) {
            continue
          }

          classList = row.classList
          if (_checked) {
            if (!classList.contains('row-checked')) {
              classList.add('row-checked')
              row.className = classList.toString()
            }
          } else {
            if (classList.contains('row-checked')) {
              classList.remove('row-checked')
              row.className = classList.toString()
            }
          }
        }
      }

      // 可能并没有checkbox
      if (!hasCheckbox) {
        checkAll = false
      }

      this.checkAll = checkAll
      this[this.page.selectedIdsKey || 'selectedIds'] = ids
    },
    onTableKeydown (e) {
      this.shiftDown = e.key === 'Shift'
    },
    onTableKeyup () {
      this.shiftDown = false
    },
    // 清空shift记录
    clearShiftIndexMark (index) {
      this._tableObject[index] = {}
    },
    setRowCheckEvent () {
      let that = this
      // 必须是.check-table才能被选中
      let tables = document.querySelectorAll('.check-table .ivu-table-body')
      if (tables.length) {
        this.shiftDown = false
        window.addEventListener('keydown', this.onTableKeydown)
        window.addEventListener('keyup', this.onTableKeyup)

        this._tableObject = {}
        for (let i = 0; i < tables.length; i++) {
          let table = tables[i]
          this._tableObject[i] = {}

          table.onclick = (e) => {
            let path = e.path
            let currentTable
            let currentRow
            for (let m = 0; m < path.length; m++) {
              // 判断是否点击了.ivu-table-row
              if (path[m].classList && path[m].classList.contains('ivu-table-row')) {
                currentRow = path[m]
              }

              if (path[m].classList && path[m].classList.contains('ivu-table-body')) {
                currentTable = path[m]
                break
              }
            }

            for (let i = 0; i < tables.length; i++) {
              if (tables[i] === currentTable) {
                let rowIndex = this.getTableRowIndex(currentTable, currentRow)

                if (this.shiftDown) {
                  this._tableObject[i].endIndex = rowIndex
                } else {
                  this._tableObject[i].startIndex = rowIndex
                  delete this._tableObject[i].endIndex
                }
              } else {
                this._tableObject[i] = {}
              }
            }
          }

          table.oncontextmenu = (e) => {
            let path = e.path
            let classList
            let currentTable
            for (let m = 0; m < path.length; m++) {
              classList = path[m].classList

              if (classList && classList.contains('ivu-table-body')) {
                currentTable = path[m]
              }

              if (classList && classList.contains('ivu-table-wrapper')) {
                break
              } else {
                classList = null
              }
            }

            if (classList) {
              let className = ''
              for (let i = 0; i < classList.length; i++) {
                className = classList[i]

                // 带下划线的就是page.list
                if (className.indexOf('_') !== -1) {
                  break
                } else {
                  className = ''
                }
              }

              let index
              for (let k = 0; k < tables.length; k++) {
                if (currentTable === tables[k]) {
                  index = k
                  break
                }
              }
              let data = this._tableObject[index]
              let startIndex = data.startIndex
              let endIndex = data.endIndex

              if (startIndex > endIndex) {
                let tempIndex = startIndex
                startIndex = endIndex
                endIndex = tempIndex
              }

              // 第一个参数得到的对象必须是page对象
              let arrtributes = ['page', 'list']
              if (className) {
                arrtributes = className.split('_')
              }

              let page = this[arrtributes[0]]
              let list = page[arrtributes[1]]
              // 默认是table
              let ref = page.ref || 'table'
              let key = page.idKey || 'id'

              // 首位必须都选中才能点击右键
              if (!(startIndex >= 0 && endIndex >= 0)) {
                return false
              }

              this.$store.commit('setTableContextMenu', {
                position: {
                  x: e.clientX,
                  y: e.clientY
                },
                checkAll () {
                  // 默认使用iview自带的checkbox
                  let map = that.checkboxMap
                  if (!map) {
                    let item
                    let refTable = that.$refs[ref]
                    for (let j = startIndex; j <= endIndex; j++) {
                      item = list[j]
                      if (!item._checked) {
                        item._checked = true
                        refTable.toggleSelect(j)
                      }
                    }
                  } else {
                    let item
                    for (let j = startIndex; j <= endIndex; j++) {
                      item = list[j]
                      if (that.checkable(item)) {
                        map[item[key]] = true
                      }
                    }

                    that.checkRows()
                  }

                  that.clearShiftIndexMark(index)
                },
                // 取消选择
                uncheckAll () {
                  let map = that.checkboxMap
                  if (!map) {
                    let refTable = that.$refs[ref]
                    let item
                    for (let j = startIndex; j <= endIndex; j++) {
                      item = list[j]
                      if (item._checked) {
                        item._checked = false
                        refTable.toggleSelect(j)
                      }
                    }
                  } else {
                    let item
                    for (let j = startIndex; j <= endIndex; j++) {
                      item = list[j]
                      if (that.checkable(item)) {
                        map[item[key]] = false
                      }
                    }

                    that.checkRows()
                  }

                  that.clearShiftIndexMark(index)
                },
                oppositeCheck () {
                  let map = that.checkboxMap
                  if (!map) {
                    let refTable = that.$refs[ref]
                    let item
                    for (let j = startIndex; j <= endIndex; j++) {
                      item = list[j]
                      item._checked = !item._checked
                      refTable.toggleSelect(j)
                    }
                  } else {
                    let item
                    for (let j = startIndex; j <= endIndex; j++) {
                      item = list[j]
                      if (that.checkable(item)) {
                        map[item[key]] = !map[item[key]]
                      }
                    }

                    that.checkRows()
                  }

                  that.clearShiftIndexMark(index)
                },
                show: true
              })
            }

            return false
          }
        }
      }
    },
    getTableRowIndex (table, row) {
      let rows = table.querySelectorAll('.ivu-table-row')
      for (let i = 0; i < rows.length; i++) {
        if (row === rows[i]) {
          return i
        }
      }
    },
    // -----------------------------------Table事件------------------------------------------------
    changePageSize (pageSize) {
      let page = this.page
      page.pageSize = pageSize
      this.util.pageValue(page.key, pageSize)

      this.getPage(1)
    },
    // -----------------------------------表单搜索------------------------------------------------
    // 带有搜索条件originForm，需要拷贝
    copyForm (form) {
      this.originForm = form
      this.searchForm = this.objectUtil.copyObject(form)
    },
    search () {
      this.originForm = this.objectUtil.copyObject(this.searchForm)
      this.getPage(1)
    }
    // -----------------------------------表单搜索------------------------------------------------
  }
}
